package com.atguigu.bigdata.spark.zzgcore.wc

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
 * @Classname Spark02_WordCount
 * @Description TODO
 * @Date 2023/9/16 19:57
 * @Author zhuzhenguo
 */
object Spark03_WordCount {
  def main(args: Array[String]): Unit = {
    //映射（map）和规约（reduce）
    val sparkConf: SparkConf = new SparkConf().setMaster("local").setAppName("WordCount")
    val sc = new SparkContext(sparkConf)

    val lines: RDD[String] = sc.textFile("datas")

    val words: RDD[String] = lines.flatMap(_.split(" "))
    val wordToOne: RDD[(String, Int)] = words.map(
      word => (word, 1)
    )

    // Spark框架提供了更多的功能，可以将分组和聚合使用一个方法实现
    // reduceByKey相同的key的数据，可以对value进行reduce聚合
//    wordToOne.reduceByKey((x, y) => {x + y})
    val worldToCount: RDD[(String, Int)] = wordToOne.reduceByKey(_ + _)
    val array: Array[(String, Int)] = worldToCount.collect()
    array.foreach(println)

    sc.stop()
  }
}
